package demo3;

import java.util.LinkedList;
import java.util.Queue;

public class MyStack {

    private Queue<Integer> qu1;
    private Queue<Integer> qu2;


    public MyStack() {
        qu1 = new LinkedList<>();
        qu2 = new LinkedList<>();
    }


    public void push(int x) {
        if(!qu1.isEmpty()){
            qu1.offer(x);
        }else if(!qu2.isEmpty()){
            qu2.offer(x);
        }else{
            qu1.offer(x);
        }
    }


    public int pop() {
        if (empty()) {
            return -1;
        }
        if (!qu1.isEmpty()) {
            int size = qu1.size();//容易犯的错误，使用qu1.size（）时，qu1.size()会随着qu1.poll()的变化而变化，则for循环次数会变少
            for (int i = 0; i < size - 1; i++) {
                int temp = qu1.poll();
                qu2.offer(temp);
            }
            return qu1.poll();
        } else {
            int size = qu2.size();
            for (int i = 0; i < size - 1; i++) {
                int temp = qu2.poll();
                qu1.offer(temp);
            }
            return qu2.poll();
        }
    }


    public int top() {
        if (empty()) {
            return -1;
        }
        int temp = -1;
        if (!qu1.isEmpty()) {
            int size = qu1.size();//容易犯的错误，使用qu1.size（）时，qu1.size()会随着qu1.poll()的变化而变化，则for循环次数会变少
            for (int i = 0; i < size; i++) {
                temp = qu1.poll();
                qu2.offer(temp);
            }
            return temp;
        } else {
            int size = qu2.size();
            for (int i = 0; i < size; i++) {
                temp = qu2.poll();
                qu1.offer(temp);
            }
            return temp;
        }
    }


    public boolean empty() {
        return qu1.isEmpty() && qu2.isEmpty();
    }




}
